<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;


class Withdrawal implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $config = [];
    protected $params = [];
    public function __construct($params)
    {
        $this->params = $params;
        $this->config = config('queue.connections.rabbitmq');
    }

    /**
     * FunctionName：handle
     * Description：
     * Author：lwl
     * @throws \Exception
     */
    public function handle()
    {
        try {
            $conn = new AMQPStreamConnection( //建立生产者与mq之间的连接
                $this->config['host'],$this->config['port'],$this->config['login'],$this->config['password'], '/'
            );
            $channel = $conn->channel(); //在已连接基础上建立生产者与mq之间的通道
            $channel->exchange_declare($this->config['exchange_name'], 'direct', false, true, false); //声明初始化交换机
            $channel->queue_declare($this->config['queue'], false, true, false, false); //声明初始化一条队列
            $channel->queue_bind($this->config['queue'], $this->config['exchange_name']); //将队列与某个交换机进行绑定，并使用路由关键字
            $msgBody = json_encode($this->params);
            $msg = new AMQPMessage($msgBody, ['content_type' => 'text/plain', 'delivery_mode' => 2]); //生成消息
            $channel->basic_publish($msg, $this->config['exchange_name']); //推送消息到某个交换机
            $channel->close();
            $conn->close();
        }catch (\Exception $exception){
            Log::info($exception->getMessage());
        }
    }
}
